<template>
  <div class="img">
    <img :src="previewImg" @click="preview" />
    <el-dialog :close-on-click-modal="false"
      title="预览"
      :visible.sync="previewVisible"
      :append-to-body="true"
    >
      <img v-if="mediaType === 1" :src="previewImg" class="preview" />
      <video v-if="mediaType === 2" :src="src" controls />
      <video v-if="mediaType === 3" :src="src" controls />
      <div v-if="mediaType === 4" class="attach" @click="downloadAttach">
        <el-button type="primary">点击查看</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFileById } from '@/api/sys/file';
export default {
  props: {
    fileId: {
      type: [Number, String],
      default: '',
    },
  },
  data() {
    return {
      previewImg: '',
      previewVisible: false,
      src: '',
    };
  },
  watch: {
    fileId: {
      handler(newVal) {
        console.log(newVal);
        if (newVal) {
          this.getImgUrl();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getImgUrl() {
      if (this.fileId) {
        console.log(this.fileId, 'fileid');
        getFileById(this.fileId).then((res) => {
          this.previewImg = res.url;
          this.src = res.url;
          this.mediaType = 1;
          if (res.mimeType === 'video/mp4') {
            this.mediaType = 2;
          }
          if (res.mimeType === 'audio/mpeg') {
            this.mediaType = 3;
            this.previewImg = require('@/assets/images/Video.png');
          }
          if (/application/.test(res.mimeType)) {
            this.mediaType = 4;
            this.previewImg = require('@/assets/images/doc.png');
          }
          this.loading = false;
        });
      }
    },
    preview() {
      if (this.mediaType === 4) {
        window.open(this.src);
      } else {
        this.previewVisible = true;
      }
    },
    downloadAttach() {
      window.open(this.src);
    },
  },
};
</script>

<style scoped>
.img {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.img img {
  width: 100%;
  max-height: 100%;
}
.preview {
  width: 100%;
  height: auto;
}
</style>
